Page({
  data: {
    logged: false, // 登录状态
    userInfo: {}, // 用户信息
    isDarkMode: false, // 是否夜间模式
    genderMap: { 1: '男', 2: '女', 0: '未知' }, // 性别映射
    collectedSongs: [],
  },

  onShow() {
    this.checkLoginStatus();
    this.initDarkMode();
    // 新增获取收藏歌曲
    this.loadCollectedSongs();
  },
  playCollectedSong(e) {
    const song = e.currentTarget.dataset.song;
    const app = getApp();
    
    // 预加载歌曲数据
    app.globalData.pendingSong = {
      id: song.id,
      name: song.name,
      ar: song.ar || [{ name: song.artist }], // 兼容旧数据格式
      al: song.al || { picUrl: song.cover },
      dt: song.duration || 0
    };

    // 跳转到播放页
    wx.navigateTo({
      url: `/pages/Song/Song?ids=${song.id}`
    });
  },
  loadCollectedSongs() {
    const songs = wx.getStorageSync('collectedSongs') || [];
    this.setData({ collectedSongs: songs });
  },
  
  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    
    if (userInfo?.nickName && userInfo?.avatarUrl) {
      this.setData({ logged: true, userInfo });
    } else {
      this.setData({ logged: false, userInfo: {} });
    }
  },

  // 获取性别文本
  getGenderText(gender) {
    return this.data.genderMap[gender] || '未填写';
  },

  // 跳转到用户详情页
  goUser() {
    wx.navigateTo({
      url: '/pages/User/User',
    });
  },

  // 跳转到登录页面
  goLogin() {
    wx.navigateTo({
      url: '/pages/Login/Login',
    });
  },

  // 退出登录
  logout() {
    wx.removeStorageSync('userInfo'); // 清除用户信息
    this.setData({
      logged: false,
      userInfo: {},
    });
    wx.showToast({
      title: '退出成功',
      icon: 'success',
    });
  },

  // 初始化夜间模式
  initDarkMode() {
    const isDarkMode = wx.getStorageSync('isDarkMode') || false;
    this.setData({ isDarkMode });
    this.applyDarkMode(isDarkMode);
  },

  // 切换夜间模式
  toggleDarkMode(event) {
    const isDarkMode = event.detail.value;
    this.setData({ isDarkMode });
    wx.setStorageSync('isDarkMode', isDarkMode);
    this.applyDarkMode(isDarkMode);
  },

  // 应用夜间模式
  applyDarkMode(isDarkMode) {
    if (isDarkMode) {
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#333333',
      });
    } else {
      wx.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#ffffff',
      });
    }
  },
});